package com.zdsx.config;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import org.springframework.http.MediaType;

import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;

@Getter
public class JsonPayload {
    private final String payload;
    private final Map<String, String> headers;

    public JsonPayload(String payload) {
        this.payload = payload;
        this.headers = Collections.emptyMap();
    }

    public JsonPayload(String payload, Map<String, String> headers) {
        this.payload = payload;
        this.headers = headers;
    }

    public static boolean isText(MediaType mediaType) {
        return mediaType.isCompatibleWith(MediaType.TEXT_HTML) || mediaType.isCompatibleWith(MediaType.TEXT_PLAIN);
    }

    public static boolean isJson(MediaType mediaType) {
        return mediaType.isCompatibleWith(MediaType.APPLICATION_JSON);
    }

    public static boolean isText(String contentType) {
        if (StrUtil.isBlank(contentType)) {
            return false;
        }
        try {
            return isText(MediaType.parseMediaType(contentType));
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isJson(String contentType) {
        if (StrUtil.isBlank(contentType)) {
            return false;
        }
        try {
            return isJson(MediaType.parseMediaType(contentType));
        } catch (Exception e) {
            return false;
        }
    }

    public static String toString(byte[] data, String characterEncoding) {
        if (data.length > 0) {
            Charset charset = characterEncoding == null ? Charset.defaultCharset() : Charset.forName(characterEncoding);
            return new String(data, charset);
        } else {
            return null;
        }
    }
}


